import store from '@/store/index.js'
import { buildUrl } from '@/utils/url.js'
import { createRequest } from './request-core.js'

let baseUrl = null

// 对外回调
const Callbacks = {
	onRequest: null,
	onResponse: null
}

//baseUrl = 'https://heymowang.com'
//baseUrl = 'http://localhost:48080'
baseUrl = 'https://heymowang.com'
//baseUrl = 'http://8.148.159.236:48080'
const requestApi = createRequest({
	onResponse (response) {
		if (response.data && response.data.code === 401) {
			const currentPages = getCurrentPages()
			const currentPage = currentPages[currentPages.length - 1]
			let returnUrl = ''
			if (currentPage) {
				returnUrl = buildUrl(currentPage.route, currentPage.options)
			}
			uni.redirectTo({
				url: buildUrl('/pages/login/login', {
					returnUrl: encodeURIComponent(returnUrl.indexOf('/') !== 0 ? ('/' + returnUrl) : returnUrl)
				})
			})
		}
		return Promise.resolve(response)
	},
	onRequest (options) {
		if (!options.header) {
		  options.header = {}
		}
		if (store.getters.tokenInfo) {
		  options.header.Authorization = store.getters.tokenInfo
		}
/*		if (options.url.indexOf('/new/') === 0) {
			options.url = '/hsmw-api-con/api' + options.url
		} else if (options.url.indexOf('/system') !== 0 && options.url.indexOf('/auth') !== 0) {
			options.url = '/hsmw-api-weapp/api' + options.url
		}*/

		options.url = '/admin-api' + options.url

		options.url = baseUrl + options.url
		options.timeout= 60000
		if (Callbacks.onRequest) {
			Callbacks.onRequest(options)
		}
	}
})

export const post = (url, data, options) => {
	return requestApi.post(url, data, options)
}

export const get = (url, params, options) => {
	return requestApi.get(url, params, options)
}

/**
 * 订阅发送请求前事件
 */
export function onRequest (fn) {
	Callbacks.onRequest = fn
}

/**
 * 订阅发送请求前事件
 */
export function onResponse (fn) {
	Callbacks.onResponse = fn
}
